/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package modelo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

/**
 *
 * @author Guille
 */
public class HTTPProxy {

    int port;
    String host;

    public HTTPProxy(String host, int port)
    {
        this.port = port;
        this.host = host;
    }

    public String doRequest(String url) throws Exception
    { 
        SocketConnection conn = (SocketConnection)Connector.open("socket://"+host+":"+port);
        DataOutputStream os = conn.openDataOutputStream();
        StringBuffer buffer = new StringBuffer();
        buffer.append("GET "+url+" HTTP/1.1\n");
        buffer.append("Host: "+host+"\n");
        buffer.append("User-Agent: Profile/MIDP-1.0 Configuration/CLDC-1.0");
        buffer.append("\r\n\r\n");
        os.write(buffer.toString().getBytes());
        
        DataInputStream is = conn.openDataInputStream();
        int c = 0;
        String info="";
        while((c=is.read())!=-1)
        {
            info=info+(char)c;
        }
        return info.substring(info.indexOf("\r\n\r\n")+5);
    }

    public int getResponseLength(String url) throws Exception
    {
        SocketConnection conn = (SocketConnection)Connector.open("socket://"+host+":"+port);
        DataOutputStream os = conn.openDataOutputStream();
        StringBuffer buffer = new StringBuffer();
        buffer.append("HEAD "+url+" HTTP/1.1\n");
        buffer.append("Host: "+host+"\n");
        buffer.append("User-Agent: Profile/MIDP-1.0 Configuration/CLDC-1.0");
        buffer.append("\r\n\r\n");
        os.write(buffer.toString().getBytes());

        DataInputStream is = conn.openDataInputStream();
        int c = 0;
        String info="";
        while((c=is.read())!=-1)
        {
            info=info+(char)c;
        }
        
        //Content-Length: XX\r\n
        int pos = info.indexOf("Content-Length:");
        String len = info.substring(pos,info.indexOf("\r\n",pos)-1);
        return Integer.parseInt(len);    
    }

}
